package com.magnificent.atlantis.client.robot.mail;

import com.magnificent.atlantis.client.robot.RobotContext;
import com.magnificent.atlantis.client.scheduler.logger.UserThreadLogger;
import com.magnificent.atlantis.client.synchronization.Synchronizer;
import com.magnificent.commons.utils.TimeConstants;
import com.magnificent.commons.utils.other.Pair;

/**
 * User: Babanin
 * Date: 14.08.2009
 * Time: 10:23:45
 */
public class Mailer extends Thread {

    private long delay;
    private RobotContext robotContext;

    public Mailer(RobotContext robotContext) {
        delay = TimeConstants.MLS_IN_SEC * 10;

        this.robotContext = robotContext;
    }

    public Mailer(long delay, RobotContext robotContext) {
        this.delay = delay;
        this.robotContext = robotContext;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            }

            try {
                sendMail();
                receiveMail();
            } catch (RuntimeException e) {
                UserThreadLogger.getInstance(robotContext).error(e.getMessage());
            }
        }
    }

    private void receiveMail() {
        if (robotContext.getPlannerData().getConfigurationContainer().getServerConfigurations().size() == 1) {
            Synchronizer.receiveMail(new Pair<String, String>(robotContext.getLogin(), robotContext.getPassword()),
                    robotContext.getPlannerData().getConfigurationContainer().getServerConfigurations().get(0), robotContext.getPlannerData());
        } else {
            throw new IllegalStateException("There are too many server configurations");
        }
    }

    private void sendMail() {
        if (robotContext.getPlannerData().getConfigurationContainer().getServerConfigurations().size() == 1) {
            Synchronizer.sendMail(new Pair<String, String>(robotContext.getLogin(), robotContext.getPassword()),
                    robotContext.getPlannerData().getConfigurationContainer().getServerConfigurations().get(0), robotContext.getPlannerData());
        } else {
            throw new IllegalStateException("There are too many server configurations");
        }
    }

    public long getDelay() {
        return delay;
    }

    public void setDelay(long delay) {
        this.delay = delay;
    }
}
